package com.shop.resource.service.impl;

import com.shop.resource.service.IEmailService;
import com.shop.resource.util.emiltool.EmailConfig;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 *
 * @author zhoulk
 * @date: 2019年05月08日  17:19
 */
@Service
public class EmailService implements IEmailService {
    @Autowired
    Configuration configuration; //freeMarker configuration
    @Autowired
    private EmailConfig emailConfig;
    @Autowired
    private JavaMailSender mailSender;

    @Override
    public Map<String, Object> sendEmailCode(String code, String email) {
        Map<String, Object> map = new HashMap<>();
        map.put("time", new Date());
        map.put("message", code);
        map.put("toUserName", email);
        String statue = sendHtmlMail(email, "注册：验证码", map, "model.ftl");
        Map<String,Object> result = new HashMap<>();
        if (statue.equals("F")) {
           result.put("success",false);
        }else{
            result.put("success",true);
        }
        return result;
    }

    private String sendHtmlMail(String to, String subject, Map<String, Object> map, String model) {
        MimeMessage message = mailSender.createMimeMessage();
        Template t; // freeMarker template
        try {
            t = configuration.getTemplate(model);
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(t, map);
            MimeMessageHelper helper = setInfoByHelper(to, subject, content, message);
            mailSender.send(message);
            return "T";
        } catch (Exception e) {
            return "F";
        }
    }

    private MimeMessageHelper setInfoByHelper(String to, String subject, String content, MimeMessage message)
            throws MessagingException {
        //true表示需要创建一个multipart message
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(emailConfig.getEmailFrom());
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        return helper;
    }
}
